package com.simple.auth.filter;

import com.simple.common.constant.CommonConstants;
import com.simple.framework.constant.HttpStatus;
import com.simple.framework.core.auth.JwtContext;
import com.simple.framework.core.domain.LoginUser;
import com.simple.framework.core.domain.R;
import com.simple.framework.core.redis.RedisService;
import com.simple.framework.utils.JwtUtil;
import com.simple.framework.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description JWT过滤器
 * @Author xiaoke
 * @Date 2024/8/10 18:00
 * @Version 1.0
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final RedisService redisService;

    public JwtAuthenticationTokenFilter(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取 token
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)) {
            //放行，让后面的过滤器执行
            filterChain.doFilter(request, response);
            return;
        }
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            WebUtils.writeJson(response, R.fail(HttpStatus.UNAUTHORIZED,"token无效"));
            return;
        }
        LoginUser loginUser = redisService.getCacheObject(CommonConstants.AUTH_USER + userId);
        if (loginUser == null) {
            WebUtils.writeJson(response, R.fail(HttpStatus.UNAUTHORIZED,"token已过期"));
            return;
        }
        JwtContext.setLoginUser(loginUser);
        //封装Authentication
        UsernamePasswordAuthenticationToken authentication
                = new UsernamePasswordAuthenticationToken(loginUser, null,loginUser.getAuthorities());
        //存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行，让后面的过滤器执行
        filterChain.doFilter(request, response);
    }
}
